#!/usr/bin/python
#coding utf-8
"""
weatheroffice - Screen scraper for Environment Canada's Weather Office website

http://potheads.ca/~cgm/weatheroffice/
cgm@potheads.ca

Version 1.1
- The HTML formating of the forecast changed slightly. Thanks to Stuart Williams
  for the patch.
"""

from urllib2 import Request, urlopen, HTTPError
from BeautifulSoup import BeautifulSoup

def parse_current_conditions(soup):
    conditions = {}

    current = soup.first('div', {'id': 'currentcond-content'})

    observed = current.first('div', {'id': 'cityobserved'})
    observed = str(observed.contents[0])

    condition = current.first('div', {'id': 'citycondition'})
    condition = str(condition.contents[0])
    conditions['condition'] = condition
    
    dt = current('dt')
    dd = current('dd')

    if len(dd) == len(dt):
        for i in range(len(dd)):
            condition = str(dt[i].contents[0])
            value = str(dd[i].contents[0])

            if condition == 'Pressure/ Tendency':
                condition = 'Pressure'
                tendency = dd[i].first('span')
                tendency = tendency['class']
                value = ' '.join((value, tendency))
            
            conditions[condition] = value
    
    return observed, conditions

def parse_text_forecast(soup):
    forecast = []

    textforecast = soup.first('div', {'id': 'citytextf'})

    issued = textforecast.first('h3').contents[0]
    issued = str(issued)

    dt = textforecast('dt')
    dd = textforecast('dd')

    if len(dt) == len(dd):
        for i in range(len(dt)):
            day = str(dt[i].contents[1].contents[0])
            dayforecast = str(dd[i].contents[0])
            forecast.append((day, dayforecast))

    return issued, forecast

class Weather:
    def __init__(self):
        self.status = None
        
        self.conditions_observed = ''
        self.conditions = {}

        self.forecast_issued = ''
        self.forecast = []

def parse(url, last_modified=None):
    weather = Weather()

    request = Request(url)
    if last_modified:
        request.add_header('If-Modified-Since', last_modified)
    try:
        f = urlopen(request)
    except HTTPError, error:
        weather.status = error.code
        return weather

    weather.status = ''
    data = f.read()
    f.close()
    
    response = f.info()
    last_modified = response['Last-Modified']
    
    f.close()

    soup = BeautifulSoup()
    soup.feed(data)

    observed, conditions = parse_current_conditions(soup)
#issued, forecast = parse_text_forecast(soup)
    
    weather.last_modified = last_modified
    weather.conditions_observed = observed
    weather.conditions = conditions
#    weather.forecast_issued = issued
#    weather.forecast = forecast 
    return weather

